import axios from "axios";
import type { AxiosInstance } from "axios";
import "element-plus/es/components/loading/style/css";
import { ElLoading } from "element-plus";
import { HYRequestInterceptors, HYRequestConfig } from "./type";
const DEFAULT_LOADING = true;

class HYRequest {
  instance: AxiosInstance;
  interceptors?: HYRequestInterceptors;
  showLoading?: boolean;
  loading?: any;
  constructor(config: HYRequestConfig) {
    this.instance = axios.create(config);
    // 是否显示加载进度
    this.showLoading =
      config.showLoading === undefined ? DEFAULT_LOADING : config.showLoading;
    // 从 config 中取出对应实例拦截器
    this.instance.interceptors.request.use(
      this.interceptors?.requestInterceptor,
      this.interceptors?.requestInterceptorCatch
    );
    this.instance.interceptors.response.use(
      this.interceptors?.responseInterceptor,
      this.interceptors?.responseInterceptorCatch
    );
    // 为所有实例添加拦截器
    this.instance.interceptors.request.use(
      (config) => {
        if (this.showLoading) {
          this.loading = ElLoading.service({
            lock: true,
            text: "Loading",
            background: "rgba(0, 0, 0, 0.2)",
            fullscreen: true,
          });
        }
        return config;
      },
      (err) => {
        return err;
      }
    );
    this.instance.interceptors.response.use(
      (res) => {
        this.loading?.close();
        return res.data;
      },
      (err) => {
        this.loading?.close();
        if (err.response.status === 404) {
          console.log("404 错误~");
        }
        return err;
      }
    );
  }

  request<T = any>(config: HYRequestConfig): Promise<T> {
    return new Promise((resolve, reject) => {
      if (config.showLoading === false) {
        this.showLoading = config.showLoading;
      }
      this.instance
        .request<T, T>(config)
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
          return err;
        })
        .finally(() => {
          this.showLoading = DEFAULT_LOADING;
        });
    });
  }

  get<T = any>(config: HYRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: "GET" });
  }
  post<T = any>(config: HYRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: "POST" });
  }
  delete<T = any>(config: HYRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: "DELETE" });
  }
  patch<T = any>(config: HYRequestConfig<T>): Promise<T> {
    return this.request<T>({ ...config, method: "PATCH" });
  }
}

export default HYRequest;
